import { useParams } from 'react-router-dom';
import { useRequest } from 'ahooks';
import { getQuestionService } from '../services/question';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { resetComponents } from '../store/componentReducer';
import { resetPageInfo } from '../store/pageInfoReducer';
function useLoadQuestionData() {
  const { id = '' } = useParams();
  const dispatch = useDispatch();

  const { loading, data, run, error } = useRequest(
    async (id: string) => {
      if (!id) {
        throw new Error('没有问卷 id');
      }
      const data = await getQuestionService(id);
      return data;
    },
    { manual: true },
  );

  useEffect(() => {
    run(id);
  }, [id, run]);

  useEffect(() => {
    if (!data) return;
    const {
      title = '',
      desc = '',
      js = '',
      css = '',
      isPublished = false,
      componentList = [],
    } = data;
    dispatch(
      resetComponents({ componentList, selectedId: '', copiedComponent: null, undoStep: 0 }),
    );
    dispatch(resetPageInfo({ title, desc, js, css, isPublished }));
    console.log('title', title, 'desc', desc, 'js', js, 'css', css, isPublished);
  }, [data, dispatch]);
  return { loading, error };
}

export default useLoadQuestionData;
